package cn.mw.cmdb.processor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.mw.cmdb.entity.*;
import cn.mw.cmdb.param.InstanceSearchParam;
import cn.mw.cmdb.param.VendorSearchParam;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.cmdb.service.impl.InstanceServiceImpl;
import cn.mw.cmdb.service.impl.ModelVendorServiceImpl;
import cn.mw.cmdb.util.AssetsTool;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.SubCondition;
import cn.mw.microMonitorCommon.api.cmdb.TreeView;

import java.util.*;
import static cn.mw.cmdb.util.ValConvertUtil.strValueConvert;

public class TreeProcessorBrand implements TreeProccessorTable{

    private CmdbServiceManage cmdbServiceManage;

    public TreeProcessorBrand(CmdbServiceManage cmdbServiceManage){
        this.cmdbServiceManage = cmdbServiceManage;
    }

    @Override
    public List genTreeData(TableDataProcessorContext context) throws Exception {
        List<TreeView> ret = new ArrayList<>();
        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        Set<String> idSet = new HashSet<>();
        InstanceSearchParam param = new InstanceSearchParam();
        BeanUtil.copyProperties(context.getTableSearchParam(), param, CopyOptions.create().setIgnoreNullValue(true));
        List<InstanceGroupBySingleAndStatus> groupList = instanceService.groupCountBySingle(CMDBTool.getFieldName(InstanceInfo::getBrandId),param);
        Map<String, List<AssetsTool.ItemAssetsStatusContext>> contextMap = AssetsTool.initGroupIdSet(idSet ,groupList);

        ModelVendorServiceImpl vendorService = (ModelVendorServiceImpl) cmdbServiceManage.getModelService(ModelVendorServiceImpl.ID);
        VendorSearchParam searchParam = new VendorSearchParam();
        SubCondition subCondition = new SubCondition(CriteriaOpsType.in.name() ,idSet.stream().toList());
        searchParam.addSubCondition(CMDBTool.getFieldName(ModelVendorInfo::getId) ,subCondition);
        List<ModelVendorInfo> vendorInfos = vendorService.selectList(searchParam);
        if(null != vendorInfos){
            ret.addAll(vendorInfos);
        }
        for(TreeView treeView : ret) {
            String id = strValueConvert(treeView.getId());
            List<AssetsTool.ItemAssetsStatusContext> contexts = contextMap.get(id);
            if (null != contexts) {
                treeView.setCount(AssetsTool.calcItemAssetsStatusCount(contexts));
                treeView.setItemAssetsStatus(AssetsTool.calcItemAssetsStatusContext(contexts, treeView));
            }
        }
        return ret;
    }
}
